package me.xuym.crawler.dygang.loader;

import com.cbs.java.component.application.Application;
import com.cbs.java.component.database.Database;
import com.cbs.java.component.database.mysql.MySqlDatabase;
import me.xuym.crawler.Processor;
import me.xuym.crawler.dygang.entity.DYGangDBResult;
import me.xuym.crawler.dygang.entity.DYGangWebResult;

import java.util.List;

/**
 * Created by broche on 13/09/2017.
 */
public class DYGangDBLoader extends Processor<List<DYGangWebResult>, List<DYGangDBResult>> {
    private int MaxUpdateDeadline = 30 * 24 * 60 * 60;
    private int MinDBRating = 6;
    private Database database;

    public DYGangDBLoader(Application application, String host, String port, String username, String password, String database) throws Exception {
        super(application);
        this.database = new MySqlDatabase(host, port, username, password, database);
        MaxUpdateDeadline = application.getProperty("MaxUpdateDeadline", 30 * 24 * 60 * 60);
        MinDBRating = application.getProperty("MinDBRating", 6);
    }

    @Override
    protected List<DYGangDBResult> onProcess(List<DYGangWebResult> dyGangWebResults) throws Exception {
        StringBuilder sql = new StringBuilder();
        sql.append("select * from dygang where 1=1 ");
        if (dyGangWebResults == null || dyGangWebResults.size() == 0) {
            sql.append(" and (updatetime - createtime < " + MaxUpdateDeadline + " and status = 0)")
                    .append(" or (dbrating > " + MinDBRating + " and status = 0)");
        } else {
            StringBuilder where = new StringBuilder();
            where.append("(");
            for (DYGangWebResult result : dyGangWebResults) {
                where.append("\"" + result.getUrl() + "\"").append(",");
            }
            where.deleteCharAt(where.length() - 1);
            where.append(")");
            sql.append(" and url in ").append(where);
        }
        List<DYGangDBResult> results = database.query(sql.toString(), DYGangDBResult.class);
        return results;
    }
}
